<template>
  <div>
    <el-input placeholder="请选择上架位置" v-model="locatorName" readonly>
      <el-button slot="suffix" type="text" class="mr5" @click="open">选择</el-button>
    </el-input>
    <el-drawer :visible.sync="show" size="70vw" append-to-body destroy-on-close :before-close="handleClose">
      <el-container class="main_container">
        <el-header height="5%">
          <el-form ref="queryParams" :model="queryParams" :inline="true" label-width="70px">
            <el-form-item label="所属库区" prop="areaId">
              <el-select v-model="queryParams.areaId" placeholder="请选择所属库区" style="width: 100%;">
                <el-option v-for="item in areaOptions" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="货柜" prop="cabinetGroupId" v-if="(ano == 'CL'||ano == 'ZX'||ano == 'DX')?false:true">
              <el-select v-model="queryParams.cabinetGroupId" placeholder="请选择所属货柜" style="width: 100%;">
                <el-option v-for="item in cabinetGroupOptions" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="位置" prop="cabinetGroupId" v-if="(ano == 'ZX'||ano == 'DX')?true:false">
              <el-select v-model="queryParams.cabinetGroupId" placeholder="请选择所属货柜" style="width: 100%;">
                <el-option v-for="item in cabinetGroupOptions" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="物品形态" prop="shape" v-if="ano == 'PT'">
              <el-select v-model="queryParams.shape" placeholder="请选择物品形态" style="width: 100%;" clearable>
                <el-option v-for="dict in dict.type.wms_property_shape" :key="dict.value" :label="dict.label"
                           :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="车辆类型" prop="cabinetGroupId" v-if="ano == 'CL'">
              <el-select v-model="queryParams.cabinetGroupId" placeholder="请选择车辆类型" style="width: 100%;">
                <el-option v-for="item in cabinetGroupOptions" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-form>
        </el-header>
        <el-main height="90%" v-loading="loading">
          <el-checkbox-group v-model="selectDatas" @change="checkboxChange">
            <template v-for="(item,ind) in dataList">
              <el-card class="box-card" shadow="hover" style="width: 32%;;float: left;margin: 5px;">
                <div slot="header" class="clearfix">
                  <div class="fl" style="margin-right: 10px;">
                    <el-checkbox :label="item.id">
                      <el-badge :value="getIndex(ind)" type="primary" style="margin-right: 5px;"/>
                    </el-checkbox>
                  </div>
                  <el-tag type="primary" effect="dark">{{ (item.cabinetName ? item.cabinetName : '') + item.name }}
                  </el-tag>
                  <el-tag type="success" class="ml10">物品数量:{{ getTotals(item.propertyVos) }}</el-tag>
                  <el-tag class="fr" v-for="dict in dict.type.wms_locator_status" v-if="dict.value == item.status">
                    {{ dict.label }}
                  </el-tag>
                </div>
                <div class="text item" style="height: 180px;overflow-y:auto;padding-top: 15px;">
                  <template v-if="item.status == 0">
                    <el-tag type="info">空闲</el-tag>
                  </template>
                  <template v-else v-for="property in item.propertyVos">
                    <el-badge :value="property.nums" class="mr20 mb20">
                      <el-tag>{{ property.name }}</el-tag>
                    </el-badge>
                  </template>
                  <template v-for="putDtl in item.putDtlVos">
                    <el-badge :value="putDtl.nums" class="mr20 mb20">
                      <el-tag type="info">{{ putDtl.name }}</el-tag>
                    </el-badge>
                  </template>
                </div>
              </el-card>
            </template>
          </el-checkbox-group>
          <template v-if="dataList.length == 0">
            <el-empty description="暂无数据"></el-empty>
          </template>
        </el-main>
        <el-footer style="color: transparent; line-height: unset;text-align: center" height="5%">
          <el-pagination
            :page-sizes="[15, 30, 60, 90]"
            layout="total, sizes, prev, pager, next"
            :pager-count="20"
            :total="total"
            :current-page.sync="queryParams.pageNum"
            :page.size.sync="queryParams.pageSize"
            @size-change="getList"
            @current-change="getList"
          />
        </el-footer>
      </el-container>
    </el-drawer>
  </div>
</template>

<script>
import { listLocator } from '@/api/wms/locator'
import { listStoreArea } from '@/api/wms/storeArea'
import { listCabinetGroup } from '@/api/wms/cabinetGroup'
import { checkPno, getRegion } from '@/api/center/index'
import { getNums } from '@/api/oms/property'
import Classify from '@/views/oms/classify'

export default {
  components: { Classify },
  dicts: ['wms_locator_status', 'wms_property_shape', 'wms_car_type'],
  props: {
    datas: {
      type: [Object]
    },
    storeId: {
      type: [String]
    },
    areaId: {
      type: [String]
    }
  },
  data() {
    return {
      show: false,
      locatorName: undefined,
      isCar: false,
      form: {},
      ano: undefined,
      loading: false,
      queryParams: {
        areaId: undefined,
        cabinetGroupId: undefined,
        shape: undefined,
        carType: undefined,
        cabinetType: undefined,
        storeId: undefined,
        makeQrcode: 1,
        showProperites: 1,
        pageNum: 1,
        pageSize: 15
      },
      isFirst: true,
      total: 0,
      dataList: [],

      //筛选条件
      areaOptions: [],
      cabinetGroupOptions: [],

      selectDatas: []
    }
  },
  watch: {
    datas: {
      handler(newVal) {
        if (newVal) {
          this.form = newVal
          this.locatorName = (newVal.areaName ? newVal.areaName + '/' : '')
            + (newVal.groupName ? newVal.groupName + '/' : '')
            + (newVal.cabinetName ? newVal.cabinetName + '/' : '')
            + (newVal.locatorName ? newVal.locatorName : '')
          this.queryParams.storeId = newVal.storeId
        }
      },
      immediate: true
    },
    storeId: {
      handler(newVal) {
        if (newVal) {
          this.queryParams.storeId = newVal
          // this.getList();
        }
      }
    },
    'queryParams.areaId': {
      handler(newVal) {
        if (newVal) {
          this.areaOptions.forEach(item => {
            if (item.id == newVal) {
              let ano = item.ano
              this.ano = ano
              if (ano == 'CL' || ano == 'ZX' || ano == 'DX') {
                this.queryParams.cabinetGroupId = undefined
                this.queryParams.cabinetType = '1'
                this.getCabinetGroup(newVal)
                // this.getList();
              } else {
                this.queryParams.cabinetType = '0'
                this.getCabinetGroup(newVal)
              }
              // this.getCabinetGroup(newVal)
            }
          })
          // this.getList();
        } else {
          this.cabinetGroupOptions = []
          this.dataList = []
        }
      },
      immediate: true,
      deep: true
    },
    'queryParams.cabinetGroupId': {
      handler(newVal, oldVal) {
        if (newVal) {
          this.getList()
        } else {
          this.dataList = []
        }
      },
      deep: true,
      immediate: true
    },
    'queryParams.carType': {
      handler(newVal, oldVal) {
        if (newVal) {
          this.getList()
        }
      },
      deep: true,
      immediate: true
    },
    'queryParams.shape': {
      handler(newVal, oldVal) {
        if (newVal) {
          this.getList()
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getTotals(items){
      if (items && items.length){
        return items.reduce((acc, {nums}) => acc + nums, 0)
      }
      return 0;
    },
    getIndex(index) {
      const currentPage = this.queryParams.pageNum - 1
      const currentPageSize = this.queryParams.pageSize
      const currentIndex = (index + 1)
      if (currentPage) {
        return currentIndex + currentPage * currentPageSize
      } else {
        return currentIndex
      }
    },
    getList() {
      this.loading = true
      listLocator(this.queryParams).then(response => {
        this.dataList = response.rows
        this.total = response.total
        this.loading = false
        this.selectDatas.push(this.datas.locatorId)
      })
    },
    checkboxChange(data) {
      if (this.selectDatas.length > 1) {
        this.selectDatas.splice(0, 1)
      }
      let locatorId = this.selectDatas[0]
      let form = {}
      this.dataList.forEach(item => {
        if (item.id == locatorId) {
          this.selectValue(item)
        }
      })
    },
    open() {
      // this.getList();
      //检测是否是车辆
      if (!this.form.boxNo) {
        checkPno(this.form.pno).then(response => {
          this.isCar = !response.data
        })
      }
      this.getStoreArea()
      this.show = true
      /**
       * 判断当前组件是否为初次加载
       * 非初次加载及重新加载数据
       */
      if (this.isFirst) {
        this.isFirst = false
      } else {
        this.getList()
      }
    },
    /** 查询库区信息 */
    getStoreArea() {
      listStoreArea({
        ano: (this.isCar ? 'CL' : undefined),
        storeId: this.queryParams.storeId ? this.queryParams.storeId : undefined
      }).then(response => {
        this.areaOptions = response.rows
        if (this.isCar) {
          this.queryParams.areaId = this.areaOptions[0].id
          // this.getList();
        } else {
          this.queryParams.areaId = this.areaId ? this.areaId : undefined
        }
      })
    },
    /** 查询智能柜信息 */
    getCabinetGroup(areaId) {
      listCabinetGroup({ areaId: areaId }).then(response => {
        this.cabinetGroupOptions = response.rows
      })
    },
    handleClose() {
      this.show = false
    },
    selectValue(data) {
      this.form.areaId = data.areaId
      this.form.locatorId = data.id
      if (this.form.boxNo) {
        this.form.items.forEach(item => {
          if (this.ano == 'CL') {
            // item.qrcode = data.qrcode;
          } else {
            item.qrcode = data.qrcode
            // setTimeout(()=>{
            //   getNums({'key':data.qrcode}).then(res=>{
            //     item.qrcode = data.qrcode + res.data;
            //   })
            // },3000)
          }
        })

        let arr = this.form.items
        var map = {}
        arr.forEach(i => {
          // 根据每一项的id进行判断，如果id相同，则应在一个新数组里
          //如果之前没有以此id为分组的数组
          if (!map[i.qrcode]) {
            // 那么创建这个组
            map[i.qrcode] = {
              qrcode: i.qrcode,
              list: [i] //list里存放完整的数据
            }
          } else {
            // 如果已经有这个数组 插入数据
            map[i.qrcode].list.push(i)
          }
        })

        //再定义一个空数组进行过滤
        let list = []
        for (var i in map) {
          list.push(map[i])
        }
        list.forEach(item => {
          let childs = item.list
          if (childs.length > 1) {
            for (let i = 1; i < childs.length; i++) {
              let qrcodes = childs[i].qrcode.split('/')
              qrcodes[1] = childs[i].region
              // qrcodes[8] = parseInt(qrcodes[8]);
              childs[i].qrcode = qrcodes.join('/')
            }
          } else {
            let qrcodes = childs[0].qrcode.split('/')
            qrcodes[1] = childs[0].region
            childs[0].qrcode = qrcodes.join('/')
          }
        })

      } else {
        // if(this.ano == 'CL'){
        // getRegion(this.form.pno).then(response=>{
        //   let region = response.msg;
        //   let qrcodes = data.qrcode.split('/')
        //   qrcodes[1] = region;
        //   this.form.qrcode = qrcodes.join('/')
        // })
        // }else{
        // this.form.qrcode = data.qrcode+this.form.pno;
        // getNums({'key':data.qrcode}).then(res=>{
        //   this.form.qrcode = data.qrcode + res.data;
        // })
        // this.form.qrcode = data.qrcode
        // }
        let qrcodes = data.qrcode.split('/')
        qrcodes[1] = this.form.region
        this.form.qrcode = qrcodes.join('/')
      }
      this.locatorName = data.areaName + '/'
        + (data.groupName ? data.groupName + '/' : '')
        + (data.cabinetName ? data.cabinetName + '/' : '')
        + data.name
      this.form.areaName = data.areaName
      this.form.groupName = data.groupName
      this.form.cabinetName = data.cabinetName
      this.$emit('update:datas', this.form)
      this.$emit('updatePutDtl', this.form)
      this.handleClose()
    }
  }
}
</script>

<style>
</style>
